package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.pojo.Myorder;
import com.chixing.pojo.OrderCarVO;
import com.chixing.pojo.OrderFlow;
import com.chixing.service.FlowService;
import com.chixing.service.OrderService;
import com.chixing.util.AlipayConfig;
import com.chixing.util.OrderUtil;
import com.chixing.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.Order;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("ali")
public class AliPayController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private FlowService flowService;

    //1.支付 ： 调用支付宝支付
    @PostMapping("pay")
    @ResponseBody
    public String pay(Integer myorderId, String productName, Long orderNum, HttpServletRequest request) {

        OrderCarVO orderCarVO = orderService.getBy2OrderId(myorderId);

        Myorder myorder = orderService.getByOrderNum(orderNum);


        System.out.println("orderCarVO:" + orderCarVO);

        //(1)初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url); // 同步请求支付
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url); // 异步请求支付


        //(3)支付请求中的订单信息  --- alirequest context
        Long out_trade_no = orderNum; //orderCarVO.getMyorder().getOrderNum();
        System.out.println("订单编号:" + out_trade_no);
        Double total_amount = orderCarVO.getMyorder().getOrderPrice();
        //Long order_Num = orderCarVO.getMyorder().getOrderNum();
        String subject = productName;
        String body = "";
        String timeout_express = "1c";
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String payResult = null;
        try {
            AlipayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:" + alipayResponse.getCode());
            System.out.println("pay getSubCode:" + alipayResponse.getSubCode());
            System.out.println("pay getMsg:" + alipayResponse.getMsg());
            System.out.println("pay isSuccess:" + alipayResponse.isSuccess());
            payResult = alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return payResult;
    }

    ;

    // 支付后的 获得 支付宝的信息 payResult --->request
    @RequestMapping("alipayReturnNotice")
    public ModelAndView returnNotice(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        System.out.println("同步返回页面操作。。。。。");


        ModelAndView mav = new ModelAndView("myorder/detail");
        mav.setViewName("myorder/detail");
        Map<String, String[]> map = request.getParameterMap();
        System.out.println(">>>>>支付后的 获得 支付宝的信息 " + map);
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) map.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
            System.out.print(name);
            System.out.print(":   ");
            System.out.println(valueStr);
        }

        mav.addObject("map", params);
        Long out_trade_no = new Long(request.getParameter("out_trade_no"));
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no"));
        //付款金额
        Double total_amount = new Double(request.getParameter("total_amount"));
//        Long order_Num = new Long(request.getParameter("order_Num"));
        /*String productName = new String(request.getParameter("productName"));*/


        System.out.println("out_trade_no:" + out_trade_no);
        System.out.println("trade_no:" + trade_no);
        System.out.println("total_amount:" + total_amount);


        Myorder myorder = orderService.getByOrderNum(Long.valueOf(params.get("out_trade_no")));

        OrderFlow orderFlow = new OrderFlow();
        orderFlow.setOrderId(myorder.getOrderId());
        orderFlow.setFlowNum(Long.valueOf(OrderUtil.getFlowCode(myorder.getCustId())));
        orderFlow.setOrderPrice(myorder.getOrderPrice());
        orderFlow.setOrderDate(myorder.getOrderDate());
        orderFlow.setCarId(myorder.getCarId());
        orderFlow.setCustId(myorder.getCustId());
        orderFlow.setOrderNum(myorder.getOrderNum());
        flowService.save(orderFlow);
        System.out.println("vipFlow流水添加成功:" + orderFlow);


        //修改订单状态
        orderService.updateMyOrderStatus(myorder.getOrderId(), 0);
        System.out.println("-----------订单状态已修改为0");

        System.out.println("********************** 支付成功(支付宝同步通知) **********************");
        System.out.println("===================订单号：" + out_trade_no);

        mav.addObject("out_trade_no", out_trade_no);
        mav.addObject("trade_no", trade_no);
        mav.addObject("total_amount", total_amount);
//        mav.addObject("order_Num",order_Num);
        /*mav.addObject("productName",productName);*/
        return mav;
    }

    @GetMapping("alipayNotifyNotice")
    @ResponseBody
    public String notifyNotice(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("异步返回页面操作。。。。。");
        Map<String, String[]> map = request.getParameterMap();
        System.out.println("支付后的 获得 支付宝的信息 " + map);
        return "myorder/detail";
    }
}